﻿#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <math.h>

//定义误差精度
#define Jindu 1e-4
//定义最大迭代次数
#define Max 20


//定义被积函数
static double f(double x) {
	return (1.0 / (1.0 + x * x));
}

int main()
{
	//初始化数据
	const double a = -4.0;
	const double b = 4.0;
	const double exact = 2.6516;
	int n = 1;
	double h = b - a;
	double T1 = h / 2.0 * (f(a) + f(b));
	double CSwucha = exact - T1;//初始误差
	double Midwucha = 0.0;//中间误差

	//打印表头
	printf("  区间数     积分         误差         误差比   \n");
	printf("-----------------------------------------------\n");
	printf("  %3d      %.4f      %+.2e \n", n, T1, CSwucha);

	//数据迭代
	int flag = 0;
	do {
		//计算函数值之和
		double sum = 0.0;
		for (int k = 1; k <= n; k++) {
			double x = a + (k - 0.5) * h;//子区间中点
			sum += f(x);
		}

		//计算新积分T2
		double T2 = 0.5 * T1 + (h / 2.0) * sum;
		double wucha = exact - T2;
		Midwucha = fabs(T2 - T1);//步3的判断依据

		//参数更新
		n *= 2;//区间数翻倍
		h /= 2.0;//步长减半
		double wuchabi = CSwucha / wucha;

		printf("  %3d      %.4f      %+.2e       %5.2f \n", n, T2,wucha,wuchabi);

		CSwucha = wucha;
		T1 = T2;
		flag++;
	} while (flag<Max && Midwucha>Jindu);
	return 0;
}